package com.ant.backstage.controller;

import com.alibaba.fastjson.JSONObject;
import com.ant.backstage.facade.ApiReturn;
import com.ant.backstage.facade.code.ApiReturnCode;
import com.ant.backstage.facade.enums.ActivityTypeEnum;
import com.ant.backstage.facade.model.User;
import com.ant.backstage.facade.request.activity.SpikeGoodsActivityRequest;
import com.ant.backstage.service.ActivityService;
import com.ant.backstage.utils.RedisUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@Api(tags = "活动")
@RequestMapping("/api/v1/activity")
public class ActivityController {

    private static Logger logger = LogManager.getLogger(ActivityController.class);

    @Resource
    private ActivityService activityService;

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private CommonMethod commonMethod;

    //秒杀活动
    @RequestMapping(value = "/spike", method = RequestMethod.GET)
    @ApiOperation(value = "秒杀接口", response = ApiReturn.class)
    public ApiReturn spikeActivity(SpikeGoodsActivityRequest spikeGoodsActivityRequest, HttpServletRequest request) {
        /**
         * 1.  开始前准备工作 活动静态页面 假地址 活动开始吐出真实地址 活动信息读取到redis中
         * 2. 活动开始用户请求 ，nginx漏桶过滤
         * 3. 进入接口 校验用户是否已经秒杀成功过，对所有请求去重，redis保持原子性减库存 将成功的请求异步下单
         *
         * https://blog.csdn.net/weixin_43122090/article/details/103652202
         **/
        ApiReturn apiReturn = new ApiReturn();
        String activityKey = "ACTIVITY::UID_" + spikeGoodsActivityRequest.getActivityUid() + "::TYPE_" + ActivityTypeEnum.GOODS_SPIKE.getCode();
        //1. 校验请求是否在活动时间内
        if (redisUtil.hasKey(activityKey)) {
            Date date = new Date();
            Date activityStartTime = (Date) redisUtil.hget(activityKey, "activityStartTime");
            Date activityEndTime = (Date) redisUtil.hget(activityKey, "activityEndTime");
//            Date activityStartTime = new Date((Long) redisUtil.hget(activityKey, "activityStartTime"));
//            Date activityEndTime = new Date((Long) redisUtil.hget(activityKey, "activityEndTime"));
            /**
             *  问题： WRONGTYPE Operation against a key holding the wrong kind of value
             *  存取的类型不一致导致
             **/
            if (activityStartTime.getTime() >= date.getTime()) {
                logger.info("活动未开始");
                apiReturn.setCode(ApiReturnCode.ACTIVITY_NO_START.getCode());
                apiReturn.setMsg(ApiReturnCode.ACTIVITY_NO_START.getMessage());
                return apiReturn;
            }
            if (activityEndTime.getTime() <= date.getTime()) {
                logger.info("活动已经结束");
                apiReturn.setCode(ApiReturnCode.ACTIVITY_END_START.getCode());
                apiReturn.setMsg(ApiReturnCode.ACTIVITY_END_START.getMessage());
                return apiReturn;
            }
        } else {
            logger.info("活动未开始");
            apiReturn.setCode(ApiReturnCode.ACTIVITY_NO_START.getCode());
            apiReturn.setMsg(ApiReturnCode.ACTIVITY_NO_START.getMessage());
            return apiReturn;
        }
        //校验用户是否已经秒杀成功过 lua脚本已经有校验
        String successKey = "ACTIVITY::UID_" + spikeGoodsActivityRequest.getActivityUid()
                + "::TYPE_" + ActivityTypeEnum.GOODS_SPIKE.getCode() + "::SUCCESS";
//        User user = commonMethod.getUserInfoByToken(request);
        //为了测试 产生数据库中的随机UID
        List<String> rodUid = new ArrayList<>();
        rodUid.add("7009da62633911ec9b34020017000b7b");
        rodUid.add("d9549dfe548c4c22b281b19364c3da77");
        rodUid.add("d9549dfe548c4c22b281b19364c3da17");
        rodUid.add("e3b0633ad7194deab0b15f7724c25bd5");
        rodUid.add("7009da62633911ec9b34020017000b7svb");
        rodUid.add("7009da62633911e84086450017000b7svb");

        User user = new User();
        user.setUid(rodUid.get((int) (Math.random()*(4-0)+0)));

        boolean b = redisUtil.hHasKey(successKey, user.getUid());
        if (b) {
                logger.warn("当前用户已经秒杀成功过一次user={}", JSONObject.toJSONString(user));
                apiReturn.setCode(ApiReturnCode.ACTIVITY_SPIKE_GOODS.getCode());
                apiReturn.setMsg(ApiReturnCode.ACTIVITY_SPIKE_GOODS.getMessage());
                return apiReturn;
        }
        //减库存 成功添加记录
        apiReturn = activityService.spikeGoodsActivity(activityKey, successKey, spikeGoodsActivityRequest, user);
        return apiReturn;
    }


}
